package io.vertx.example.verticle;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.buffer.Buffer;
import io.vertx.example.bean.DirectConnectBean;
import io.vertx.example.util.ProxyUtils;
import io.vertx.example.util.Runner;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhouwenqing 2018-12-29 
 */
public class ForwardConnectMonitor extends AbstractVerticle {
    private static final Logger log = LoggerFactory.getLogger(ForwardConnectMonitor.class);
    private Map<String, DirectConnectBean> hBeans = new HashMap<>();
    private long lastModifiedTime = -1L;

    private String FORWARD_CONFIG_FILE = "forward_connect.json";

    public static void main(String[] args) {
        Runner.runExample(ForwardConnectMonitor.class);
    }

    protected void reloadConfig(){
        lastModifiedTime = System.currentTimeMillis();
        vertx.fileSystem().readFile(FORWARD_CONFIG_FILE,  rs->{
            if(rs.succeeded()){
                Buffer buf = rs.result();

                String jsonStr = buf.getString(0,buf.length(),"UTF-8");
                log.debug("读取到的文件内容：{}", jsonStr);
                List<DirectConnectBean> beans = ProxyUtils.readJson(jsonStr, List.class, DirectConnectBean.class);
                for(DirectConnectBean bean :beans){
                    DirectConnectBean oldBean = hBeans.get(bean.getConfigId());
                    if(oldBean!=null){
                        if(oldBean.equals(bean) && oldBean.getDeployId()!=null ){
                            continue;
                        }
                        if(oldBean.getDeployId()!=null){
                            log.info("try to old stop {}", oldBean);
                            vertx.undeploy(oldBean.getDeployId(), unDeployRs->{
                                deployNewBean(bean);
                            });
                            continue;
                        }

                    }
                    deployNewBean(bean);
                }
            }

        });
    }
    protected void deployNewBean(DirectConnectBean bean){

        hBeans.put(bean.getConfigId(), bean);
        ForwardConnectVerticle client = new ForwardConnectVerticle(bean);
        vertx.deployVerticle(client, deployRs->{
            if( deployRs.succeeded() ){
                bean.setDeployId( client.deploymentID() );
                log.info("forward connect bean deploy success {}", bean);
            }else{
                bean.setDeployId( null );
                log.error("forward connect bean deploy fail {}", bean);
            }
        });
    }
    @Override
    public void start() {
        String configFile = new File(FORWARD_CONFIG_FILE).getAbsolutePath();
        log.info("启动成功，准备从{}读取配置", configFile);
        reloadConfig();

        vertx.setPeriodic(10000L, h->{
            vertx.fileSystem().lprops(FORWARD_CONFIG_FILE, rs->{
                if( rs.succeeded() ){
                    if( rs.result().lastModifiedTime() > lastModifiedTime){
                        log.info("forward_connect file changed, try to reload");
                        reloadConfig();
                        lastModifiedTime = rs.result().lastModifiedTime();
                    }
                }
            });
        });
    }



}
